const moment = require('./../utils/node_modules/moment');
const types = {
	// 初始化用户
	initBaseInfo: "initBaseInfo",
	// 登录
	login: "login",
	// 退出
	loginout: "loginout",
	// 签到
	sign:"sign",
	// 校验是否第二天
	check2Days:"check2Days",
	// 校验token是否已过期
	checkToken:"checkToken",
	// 获取账户信息
	getAccoundinfo:"getAccoundinfo",
	// 是否字符
	useWords:"useWords"
}
const uniIdCo = uniCloud.importObject("uni-id-co");
const zmfDbClient = uniCloud.importObject("zmf-db-client");
export default {
	namespaced: true,
	state: {
		userinfo: undefined,
		accountinfo: undefined,
		scores:undefined,
		signed:false,
		signedList:[],
		signedTimes:undefined,
		token_expire:false
	},
	getters: {

	},
	mutations: {
		[types.initBaseInfo](state) {
			try {
				const value = uni.getStorageSync('cu-userinfo');
				if (value) {
					state.userinfo = JSON.parse(value)
					state.token_expire = false
				}
			} catch (e) {
				console.error('StorageSync异常-key:cu-userinfo')
			}
			try {
				const value = uni.getStorageSync('cu-accountinfo');
				if (value) {
					state.accountinfo = JSON.parse(value)
				}
			} catch (e) {
				console.error('StorageSync异常-key:cu-accountinfo')
			}
			try {
				const value = uni.getStorageSync('cu-scores');
				if (value) {
					const scores =  JSON.parse(value)
					state.scores = scores;
					const date = new Date().getTime();
					const week = moment(date).day();
					state.signed = false
					state.signedList = []
					let count = 0;
					for (let score of scores) {
						if(score && score.type === 1) {
							if(count > week){
								break;
							}
							
							if (count === 0){
								// 判断当日是否已签到
								if (moment(date).format("YYYYMMDD") === moment(score.create_date).format("YYYYMMDD")) {
									state.signed = true;
									state.signedList.unshift(moment(score.create_date).day());
									state.signedTimes = date
									count++;
									continue;
								}
								
							}
							
							// 判断是否是一周之内
							if(score.create_date > moment(moment(date).format("YYYYMMDD")).subtract(week, 'd').valueOf() ){
								state.signedList.unshift(moment(score.create_date).day())
							}
							
							count++;
							
						}
					}
			
				}
			} catch (e) {
				console.error('StorageSync异常-key:cu-scores',e)
			}
		},
		[types.loginout](state) {
			try {
				const value = uni.getStorageSync('cu-userinfo');
				if (value) {
					state.userinfo = undefined
					uni.removeStorageSync('cu-userinfo');

				}
			} catch (e) {
				console.error('StorageSync异常-key:cu-userinfo')
			}
			try {
				const value = uni.getStorageSync('cu-accountinfo');
				if (value) {
					state.accountinfo = undefined
					uni.removeStorageSync('cu-accountinfo');

				}
			} catch (e) {
				console.error('StorageSync异常-key:cu-accountinfo')
			}
			try {
				const value = uni.getStorageSync('cu-scores');
				if (value) {
					state.scores = undefined
					state.signed = false
					state.token_expire = false
					state.signedList = []
					state.signedTimes = undefined
					uni.removeStorageSync('cu-scores');
			
				}
			} catch (e) {
				console.error('StorageSync异常-key:cu-scores')
			}
			uni.navigateBack({
				delta: 1,
				animationType: 'pop-out',
				animationDuration: 200
			});
		},
		async [types.sign](state){
			if(state.signed){
				console.error("当日已签到")
				return
			}
			const date = new Date().getTime()
			let signParam = {
				user_id:state.userinfo._id,
				score:10,
				balance:10,
				type:1,
				comment:"签到奖励",
				create_date: date
			}
			if(state.scores && state.scores.length > 0){
				//  moment().subtract(1, 'days')
				const lastDateTime = moment(moment(date).format("YYYYMMDD")).subtract(1, 'days').valueOf();
				let lastTimes = undefined;
				let lastBalance = undefined;
				for (let i = 0; i < state.scores.length; i++) {
					if(i == 0){
						lastBalance = state.scores[i].balance
					}
					if(state.scores[i].type === 1){
						lastTimes = state.scores[i].create_date;
						break
					}
				}
				if(lastTimes >= lastDateTime){
					signParam.score = 20
					signParam.comment = "连续签到奖励"
				}
				signParam.balance = lastBalance + signParam.score
			}
			
			const resp = await zmfDbClient.addUniIdScores(signParam);
			state.scores.unshift(signParam);
			state.signed = true
			state.signedList.push(moment(date).day())
		},
		[types.check2Days](state) {
			if(state.signedTimes !== undefined){
				const date = moment(new Date().getTime()).format("YYYYMMDD");
				if(date !== moment(state.signedTimes).format("YYYYMMDD")){
					state.signed = false
				}
			}
		},
		[types.checkToken](state) {
			uni.clearStorageSync();
			state.userinfo= undefined;
			state.accountinfo= undefined;
			state.scores=undefined;
			state.signed=false;
			state.signedList=[];
			state.token_expire = true
		},
		[types.getAccoundinfo](state,{data,scores}) {
			state.accountinfo= data;
			state.scores= scores;
		},
		async [types.useWords](state,{uid,useWords}) {
			for (let i = 0; i < state.accountinfo.length; i++) {
				let accountinfo = state.accountinfo[i]
				const residue = accountinfo.words - accountinfo.used
				if(accountinfo.use_up_mark === false && residue >= useWords){
					const mark = (useWords + accountinfo.used) === accountinfo.words ? true : false
					// 创建参数
					const accountinfoParam = {
						uid:uid,
						_id:accountinfo._id,
						used: useWords + accountinfo.used,
						use_up_mark: mark
					}
					await zmfDbClient.updateZmfAccountInfo(accountinfoParam);
					state.accountinfo[i].use_up_mark = mark
					state.accountinfo[i].used = useWords + accountinfo.used
					break;
				}
				else if(accountinfo.use_up_mark === false && residue > 0 && residue <= useWords) {
					// 创建参数
					const accountinfoParam = {
						uid:uid,
						_id:accountinfo._id,
						used: accountinfo.words,
						use_up_mark: true
					}
					await zmfDbClient.updateZmfAccountInfo(accountinfoParam);
					useWords = useWords - residue
					state.accountinfo[i].use_up_mark = true
					state.accountinfo[i].used = accountinfo.words
				}
			}
		}
	},
	actions: {
		/* 初始化用户 */
		initBaseInfo({
			commit
		}) {
			commit(types.initBaseInfo)
		},
		/* login */
		async login({commit,dispatch}, {code}) {
			const data = {
				code: code,
				inviteCode: ""
			}
			// 微信登录
			const loginResp = await uniIdCo.loginByWeixin(data);
			// 根据uid查询数据库信息
			const {
				uid
			} = loginResp;
			const accountInfoResp = await zmfDbClient.getUserInfo({
				uid
			});
			const {
				_id,
				wx_openid,
				nickname,
				username,
				role
			} = accountInfoResp.userRecord;

			let userinfo = {
				_id,
				wx_openid,
				nickname,
				username,
				role
			}
			// 判断是否存在username,存在说明已注册，不存在则重新生成
			if (!username) {
				let random = Math.round(Math.random() * 1000);
				if (random < 1000) {
					random = random + "";
					const len = random.length
					for (let i = 0; i < (4 - len); i++) {
						random = "0" + random
					}
				}
				const times = new Date().getTime();
				const id = random + times;
				const updateUserParam = {
					uid,
					username: "fy" + id,
					nickname: "坊友" + id,
					status: 0
				}
				const userInfoResp = await zmfDbClient.updateUser(updateUserParam);
				userinfo.username = updateUserParam.username;
				userinfo.nickname = updateUserParam.nickname;

				// 新增账户信息
				const curTimes = new Date().getTime();
				const expireTimes = moment(curTimes).add(30, 'days').valueOf();
				const addAccountinfoParam = {
					uid: uid,
					type: "text2audio",
					source: 1,
					create_date: curTimes,
					expire_date: expireTimes,
					words: 10000,
					used: 0,
					use_up_mark: false
				}
				const resp = await zmfDbClient.addZmfAccountInfo(addAccountinfoParam);
				uni.setStorageSync("cu-accountinfo", JSON.stringify(addAccountinfoParam));
			} else {
				const addAccountinfoParam = {
					uid: uid,
					type: "text2audio",
					expire_date: new Date().getTime()
				}
				const resp = await zmfDbClient.getZmfAccountInfo(addAccountinfoParam);
				const {errCode,userRecord} = resp;
				uni.setStorageSync("cu-accountinfo", JSON.stringify(userRecord));
			}

			uni.setStorageSync("cu-userinfo", JSON.stringify(userinfo));
			
			// 获取积分信息
			if(true){
				const scoresParams = {
					user_id:uid
				}
				const scoresResp = await zmfDbClient.getUniIdScores(scoresParams);
				const {errCode,userRecord} = scoresResp;
				
				uni.setStorageSync("cu-scores", JSON.stringify(userRecord));
			}
			
			await dispatch('initBaseInfo');
			uni.navigateBack();

		},
		/* 退出 */
		loginout({
			commit
		}) {
			commit(types.loginout)
		},
		/* 签到 */
		sign({commit}){
			commit(types.sign)
		},
		/* 校验是否第二天 */
		check2Days({commit}){
			commit(types.check2Days)
		},
		/* 校验token是否已过期 */
		async checkToken({commit}){
			const param = {
				user_id: "00",
				start_num:0,
				page_num:1
			}
			try{
				if(this.$store.state.loginStore.userinfo !== undefined){
					const resp = await zmfDbClient.getUniIdScoresByPage(param)
					const {code} = resp
					if(code === 30203){
						// uni.navigateTo({url: "/pages/oauth/loginbywx/loginbywx"});
						commit(types.checkToken)
					}
				}
			}catch(e){
				//TODO handle the exception
			}
			
		},
		async getAccoundinfo({commit,dispatch},{uid}){
			const addAccountinfoParam = {
				uid: uid,
				type: "text2audio",
				expire_date: new Date().getTime()
			}
			const resp = await zmfDbClient.getZmfAccountInfo(addAccountinfoParam);
			const {errCode,userRecord} = resp;
			if(errCode !== 0){
				uni.showToast({
					icon:'error',
					title:"获取数据失败",
					duration:2000
				})
				return
			}
			uni.setStorageSync("cu-accountinfo", JSON.stringify(userRecord));
			// 获取积分信息
			const scoresParams = {
				user_id:uid
			}
			const scoresResp = await zmfDbClient.getUniIdScores(scoresParams);
			
			uni.setStorageSync("cu-scores", JSON.stringify(scoresResp.userRecord));
			await dispatch('initBaseInfo');
			commit(types.getAccoundinfo,{data:userRecord,scores:scoresResp.userRecord})
		},
		useWords({commit},{uid,useWords}){
			commit(types.useWords,{uid,useWords})
		}
	}
}